var chatContainer = $("#chat-history")
var USERNAME = ''

function getCurrentFormattedDate() {
    var now = new Date();

    var year = now.getFullYear();
    var month = ('0' + (now.getMonth() + 1)).slice(-2); // 月份从 0 开始，所以需要加 1
    var day = ('0' + now.getDate()).slice(-2);
    var hours = ('0' + now.getHours()).slice(-2);
    var minutes = ('0' + now.getMinutes()).slice(-2);
    var seconds = ('0' + now.getSeconds()).slice(-2);

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 发送消息
function sendMessage() {
    var message = $("#input-message").val()
    var sendData = {
        username: USERNAME,
        message: message,
        sendTime: getCurrentFormattedDate()
    }
    if (message.length > 0 && USERNAME.length > 0) {
        // 基于 ajax实现将用户输入的文本发送到后台
        $.ajax({
            url: `${BASE_URL}api/chat/poll/send/message`,
            type: "POST",
            dataType: "JSON",
            data: JSON.stringify(sendData),
            success: function (resp) {
                console.log(resp)
                $("#input-message").val("")
            }
        })
    }
}

// 每隔2s向后台发起请求获取数据并展示在页面上
var maxIndex = { value: 0 }
setInterval(function () {
    $.ajax({
        url: `${BASE_URL}api/chat/poll/get/messages`,
        type: "GET",
        dataType: "JSON",
        data: {
            startIndex: maxIndex.value
        },
        success: function (resp) {
            var dataArray = resp.data
            maxIndex.value = resp.maxIndex
            $.each(dataArray, function (index, item) {
                var messageItem = $('<div class="message-item"></div>')
                var textItem = $('<div></div>')
                textItem.text(item.message)
                var nameItem = $('<div class="message-name"></div>')
                nameItem.text(`${item.username} - ${item.sendTime}`)
                messageItem.append(nameItem)
                messageItem.append(textItem)
                chatContainer.append(messageItem)
            })
        }
    })
}, 2000)